﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Globalization;

namespace _00365.Employees.Controls
{
    public partial class EmployeeForm : System.Web.UI.UserControl
    {

        protected string Action
        {
            get
            {
                return Session["EmployeeFormAction"].ToString();
            }
            set
            {
                Session["EmployeeFormAction"] = value;
            }
        }

        protected Data.Employee CurrentEmployee
        {
            get
            {
                return (Data.Employee)Session["CurrentEmployee"];
            }
            set
            {
                Session["CurrentEmployee"] = value;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            this.Disposed += new EventHandler(EmployeeForm_Disposed);
            Page.MaintainScrollPositionOnPostBack = true;

            if (!IsPostBack)
            {
                LoadBaseData();
                if (Request.Url.AbsoluteUri.Contains("AddEmployee.aspx"))
                {
                    this.Action = "Add";
                    this.CurrentEmployee = new Data.Employee();
                    this.CurrentEmployee.Id = Guid.NewGuid();
                }
                if (Request.Url.AbsoluteUri.Contains("EditEmployee.aspx"))
                {
                    this.Action = "Edit";
                    Guid EmployeeId = (Request.QueryString.AllKeys.Contains("employee") ? new Guid(Request.QueryString.Get("employee")) : new Guid());
                    if (!EmployeeId.Equals(new Guid()))
                    {
                        this.CurrentEmployee = Biz.Employee.Get(EmployeeId);
                        Fill();
                    }
                }
            }
        }

        protected void EmployeeForm_Disposed(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Session.Remove("CurrentEmployee");
            }
        }

        private void Fill()
        {
            CultureInfo ptBR = new CultureInfo("pt-BR");

            txtFullName.Text = CurrentEmployee.FullName.ToString();
            txtCPF.Text = CurrentEmployee.CPF.ToString();
            txtBirthDate.Text = CurrentEmployee.BirthDate.ToString("dd/MM/yyyy", ptBR);
            ddlGender.SelectedValue = CurrentEmployee.Gender.ToString();
            ddlSchoolDegree.SelectedValue = CurrentEmployee.SchoolDegree.ToString();
            txtOccupation.Text = CurrentEmployee.Occupation.ToString();
            ddlMarriageStatus.SelectedValue = CurrentEmployee.MarriageStatus;
            ddlSubsidiary.SelectedValue = CurrentEmployee.Subsidiary.ToString();
            txtPosition.Text = CurrentEmployee.Position.ToString();
            txtDepartment.Text = CurrentEmployee.Department.ToString();
            txtPeriod.Text = CurrentEmployee.Period.ToString();
            txtRevenue.Text = String.Format(ptBR, "{0:0,0.00}", CurrentEmployee.Revenue);
            txtHiringDate.Text = CurrentEmployee.HiringDate.ToString("dd/MM/yyyy", ptBR);
            txtEmail.Text = CurrentEmployee.Email.ToString();
            ddlUnionized.SelectedValue = CurrentEmployee.Unionized.ToString();

            grdEmployeeAddress.DataSource = CurrentEmployee.Addresses;
            grdEmployeePhone.DataSource = CurrentEmployee.Phones;
            grdEmployeeDependent.DataSource = CurrentEmployee.fnc_EmployeeDependent;

            grdEmployeeAddress.DataBind();
            grdEmployeePhone.DataBind();
            grdEmployeeDependent.DataBind();
        }

        private void LoadBaseData()
        {
            //load Subsidiaries
            ddlSubsidiary.DataSource = Biz.Company.GetSubsidiaries();
            ddlSubsidiary.DataBind();
            ddlSubsidiary.Items.Insert(0, new ListItem("Selecione...", (new Guid()).ToString()));
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (!this.Validate())
            {
                //Failed fields validation actions goes here
            }

            DateTime outBirthDate = new DateTime(1900, 1, 1);
            DateTime.TryParse(txtBirthDate.Text.Trim(), out outBirthDate);

            decimal outRevenue = 0;
            decimal.TryParse(txtRevenue.Text.Trim(), out outRevenue);

            DateTime outHiringDate = new DateTime(1900, 1, 1);
            DateTime.TryParse(txtHiringDate.Text.Trim(), out outHiringDate);

            CurrentEmployee.FullName = txtFullName.Text.Trim();
            CurrentEmployee.CPF = txtCPF.Text.Trim();
            CurrentEmployee.BirthDate = outBirthDate;
            CurrentEmployee.Gender = ddlGender.SelectedValue;
            CurrentEmployee.SchoolDegree = ddlSchoolDegree.SelectedValue;
            CurrentEmployee.Occupation = txtOccupation.Text.Trim();
            CurrentEmployee.MarriageStatus = ddlMarriageStatus.SelectedValue;
            CurrentEmployee.Subsidiary = new Guid(ddlSubsidiary.SelectedValue);
            CurrentEmployee.Position = txtPosition.Text.Trim();
            CurrentEmployee.Department = txtDepartment.Text.Trim();
            CurrentEmployee.Period = txtPeriod.Text.Trim();
            CurrentEmployee.Revenue = outRevenue;
            CurrentEmployee.HiringDate = outHiringDate;
            CurrentEmployee.Email = txtEmail.Text.Trim();
            CurrentEmployee.Unionized = (ddlUnionized.SelectedValue.Equals("True") ? true : false);

            if (this.Action == "Add")
            {
                Biz.Employee.Add(CurrentEmployee, Session);
                Response.Redirect("~/Employees/ManageEmployees.aspx");
            }
            else //editing
            {
                Biz.Employee.Update(CurrentEmployee, Session);
                Response.Redirect("~/Employees/ManageEmployees.aspx");
            }
        }

        private bool Validate()
        {
            //Validate fields acording to expected standard entries
            return true;
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Employees/ManageEmployees.aspx");
        }

        #region Confirm Delete Message Related

        protected void btnDeleteMsgYes_Click(object sender, EventArgs e)
        {
            switch (hidDeleteAction.Value)
            {
                case "Address":
                    this.CurrentEmployee.Addresses.Remove(
                        this.CurrentEmployee.Addresses.FirstOrDefault(i => i.Id == new Guid(hidDeleteItemId.Value)));
                    grdEmployeeAddress.DataSource = this.CurrentEmployee.Addresses;
                    grdEmployeeAddress.DataBind();

                    hidDeleteAction.Value = "";
                    hidDeleteItemId.Value = "";
                    popDeleteMsg.Hide();
                    break;
                case "Dependent":
                    this.CurrentEmployee.fnc_EmployeeDependent.Remove(
                        this.CurrentEmployee.fnc_EmployeeDependent.FirstOrDefault(i => i.Id == new Guid(hidDeleteItemId.Value)));
                    grdEmployeeDependent.DataSource = this.CurrentEmployee.fnc_EmployeeDependent;
                    grdEmployeeDependent.DataBind();

                    hidDeleteAction.Value = "";
                    hidDeleteItemId.Value = "";
                    popDeleteMsg.Hide();
                    break;
                case "Phone":
                    this.CurrentEmployee.Phones.Remove(
                        this.CurrentEmployee.Phones.FirstOrDefault(i => i.Id == new Guid(hidDeleteItemId.Value)));
                    grdEmployeePhone.DataSource = this.CurrentEmployee.Phones;
                    grdEmployeePhone.DataBind();

                    hidDeleteAction.Value = "";
                    hidDeleteItemId.Value = "";
                    popDeleteMsg.Hide();
                    break;
                default:
                    break;
            }
        }

        protected void btnDeleteMsgNo_Click(object sender, EventArgs e)
        {
            hidDeleteAction.Value = "";
            hidDeleteItemId.Value = "";
            popDeleteMsg.Hide();
        }

        protected void btnCloseNewUser_Click(object sender, EventArgs e)
        {
            popDeleteMsg.Hide();
        }

        #endregion

        #region DEPENDENTS

        protected void btnCancelEditDependent_Click(object sender, EventArgs e)
        {
            btnCancelEditDependent.Visible = false;
            hidEditDependent.Value = "";
            btnAddEditDependent.Text = "Adicionar Dependente";
            ddlDependentType.SelectedIndex = 0;
            txtDependentFullName.Text = string.Empty;
            txtDependentBirthDate.Text = string.Empty;
        }

        protected void btnAddEditDependent_Click(object sender, EventArgs e)
        {

            Data.EmployeeDependent newDependent = new Data.EmployeeDependent();

            if (!string.IsNullOrEmpty(hidEditDependent.Value))
            {
                newDependent = this.CurrentEmployee.fnc_EmployeeDependent.FirstOrDefault(i => i.Id == new Guid(hidEditDependent.Value));
            }
            else
            {
                newDependent.Id = Guid.NewGuid();
            }
            newDependent.DependentType = ddlDependentType.SelectedValue;
            newDependent.FullName = txtDependentFullName.Text.Trim();
            newDependent.BirthDate = Convert.ToDateTime(txtDependentBirthDate.Text.Trim());

            if (string.IsNullOrEmpty(hidEditDependent.Value))
            {
                this.CurrentEmployee.fnc_EmployeeDependent.Add(newDependent);
            }

            grdEmployeeDependent.DataSource = this.CurrentEmployee.fnc_EmployeeDependent;
            grdEmployeeDependent.DataBind();

            ddlDependentType.SelectedIndex = 0;
            txtDependentFullName.Text = string.Empty;
            txtDependentBirthDate.Text = string.Empty;

            btnCancelEditDependent.Visible = false;
            hidEditDependent.Value = "";
            btnAddEditDependent.Text = "Adicionar Dependente";
        }

        protected void grdEmployeeDependent_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteDependent":
                    hidDeleteAction.Value = "Dependent";
                    hidDeleteItemId.Value = e.CommandArgument.ToString();
                    lblDeleteMsg.Text = "Deseja realmente excluir este dependente do cadastro?";
                    lblDeleteMsgTitle.Text = "Excluir dependente";
                    popDeleteMsg.Show();
                    break;
                case "EditDependent":
                    LoadDependent(new Guid(e.CommandArgument.ToString()));
                    hidEditDependent.Value = e.CommandArgument.ToString();
                    btnCancelEditDependent.Visible = true;
                    btnAddEditDependent.Text = "Salvar";
                    break;
                default:
                    break;
            }
        }

        private void LoadDependent(Guid Id)
        {
            Data.EmployeeDependent dependent = this.CurrentEmployee.fnc_EmployeeDependent.FirstOrDefault(i => i.Id == Id);
            if (dependent != null)
            {
                ddlDependentType.SelectedValue = dependent.DependentType;
                txtDependentFullName.Text = dependent.FullName;
                txtDependentBirthDate.Text = dependent.BirthDate.ToShortDateString();

                txtDependentFullName.Focus();
            }
        }

        #endregion

        #region PHONES

        protected void btnCancelEditPhone_Click(object sender, EventArgs e)
        {
            btnCancelEditPhone.Visible = false;
            hidEditPhone.Value = "";
            btnAddEditPhone.Text = "Adicionar Telefone";
            ddlPhoneType.SelectedIndex = 0;
            txtPhoneCountryCode.Text = string.Empty;
            txtPhoneAreaCode.Text = string.Empty;
            txtPhoneNumber.Text = string.Empty;
            txtPhoneExtension.Text = string.Empty;
        }

        protected void btnAddEditPhone_Click(object sender, EventArgs e)
        {

            Data.EmployeePhone newPhone = new Data.EmployeePhone();

            if (!string.IsNullOrEmpty(hidEditPhone.Value))
            {
                newPhone = this.CurrentEmployee.Phones.FirstOrDefault(i => i.Id == new Guid(hidEditPhone.Value));
            }
            else
            {
                newPhone.Id = Guid.NewGuid();
            }
            newPhone.PhoneType = ddlPhoneType.SelectedValue;
            newPhone.CountryCode = Convert.ToInt32(txtPhoneCountryCode.Text.Trim());
            newPhone.AreaCode = Convert.ToInt32(txtPhoneAreaCode.Text.Trim());
            newPhone.PhoneNumber = Convert.ToInt32(txtPhoneNumber.Text.Trim());
            if (!string.IsNullOrEmpty(txtPhoneExtension.Text.Trim()))
                newPhone.Extension = Convert.ToInt16(txtPhoneExtension.Text.Trim());
            else
                newPhone.Extension = null;


            if (string.IsNullOrEmpty(hidEditPhone.Value))
            {
                this.CurrentEmployee.Phones.Add(newPhone);
            }

            grdEmployeePhone.DataSource = this.CurrentEmployee.Phones;
            grdEmployeePhone.DataBind();

            ddlPhoneType.SelectedIndex = 0;
            txtPhoneCountryCode.Text = string.Empty;
            txtPhoneAreaCode.Text = string.Empty;
            txtPhoneNumber.Text = string.Empty;
            txtPhoneExtension.Text = string.Empty;

            btnCancelEditPhone.Visible = false;
            hidEditPhone.Value = "";
            btnAddEditPhone.Text = "Adicionar Telefone";
        }

        protected void grdEmployeePhone_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeletePhone":
                    hidDeleteAction.Value = "Phone";
                    hidDeleteItemId.Value = e.CommandArgument.ToString();
                    lblDeleteMsg.Text = "Deseja realmente excluir este telefone do cadastro?";
                    lblDeleteMsgTitle.Text = "Excluir telefone";
                    popDeleteMsg.Show();
                    break;
                case "EditPhone":
                    LoadPhone(new Guid(e.CommandArgument.ToString()));
                    hidEditPhone.Value = e.CommandArgument.ToString();
                    btnCancelEditPhone.Visible = true;
                    btnAddEditPhone.Text = "Salvar";
                    break;
                default:
                    break;
            }
        }

        private void LoadPhone(Guid Id)
        {
            Data.EmployeePhone phone = this.CurrentEmployee.Phones.FirstOrDefault(i => i.Id == Id);
            if (phone != null)
            {
                ddlPhoneType.SelectedValue = phone.PhoneType;
                txtPhoneCountryCode.Text = phone.CountryCode.ToString();
                txtPhoneAreaCode.Text = phone.AreaCode.ToString();
                txtPhoneNumber.Text = phone.PhoneNumber.ToString();
                txtPhoneExtension.Text = phone.Extension.ToString();

                txtPhoneCountryCode.Focus();
            }
        }

        #endregion

        #region ADDRESSES

        protected void btnCancelEditAddress_Click(object sender, EventArgs e)
        {
            btnCancelEditAddress.Visible = false;
            hidEditAddress.Value = "";
            btnAddAddress.Text = "Adicionar Endereço";
            ddlAddressType.SelectedIndex = 0;
            txtAddress.Text = string.Empty;
            txtAddressNumber.Text = string.Empty;
            txtAdditionalAddress.Text = string.Empty;
            txtZipCode.Text = string.Empty;
            txtNeighborhood.Text = string.Empty;
            txtCity.Text = string.Empty;
            ddlState.SelectedIndex = 0;
            txtCountry.Text = string.Empty;
        }

        protected void btnAddAddress_Click(object sender, EventArgs e)
        {

            Data.EmployeeAddress newAddress = new Data.EmployeeAddress();

            if (!string.IsNullOrEmpty(hidEditAddress.Value))
            {
                newAddress = this.CurrentEmployee.Addresses.FirstOrDefault(i => i.Id == new Guid(hidEditAddress.Value));
            }
            else
            {
                newAddress.Id = Guid.NewGuid();
            }
            newAddress.AddressType = ddlAddressType.SelectedValue;
            newAddress.Address = txtAddress.Text.Trim();
            newAddress.Number = txtAddressNumber.Text.Trim();
            newAddress.AdditionalAddress = txtAdditionalAddress.Text.Trim();
            newAddress.ZipCode = txtZipCode.Text.Trim();
            newAddress.Neighborhood = txtNeighborhood.Text.Trim();
            newAddress.City = txtCity.Text.Trim();
            newAddress.State = ddlState.SelectedValue;
            newAddress.Country = txtCountry.Text.Trim();

            if (string.IsNullOrEmpty(hidEditAddress.Value))
            {
                this.CurrentEmployee.Addresses.Add(newAddress);
            }

            grdEmployeeAddress.DataSource = this.CurrentEmployee.Addresses;
            grdEmployeeAddress.DataBind();

            ddlAddressType.SelectedIndex = 0;
            txtAddress.Text = string.Empty;
            txtAddressNumber.Text = string.Empty;
            txtAdditionalAddress.Text = string.Empty;
            txtZipCode.Text = string.Empty;
            txtNeighborhood.Text = string.Empty;
            txtCity.Text = string.Empty;
            ddlState.SelectedIndex = 0;
            txtCountry.Text = string.Empty;
            btnCancelEditAddress.Visible = false;
            hidEditAddress.Value = "";
            btnAddAddress.Text = "Adicionar Endereço";
        }

        protected void grdEmployeeAddress_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            switch (e.CommandName)
            {
                case "DeleteAddress":
                    hidDeleteAction.Value = "Address";
                    hidDeleteItemId.Value = e.CommandArgument.ToString();
                    lblDeleteMsg.Text = "Deseja realmente excluir este endereço do cadastro?";
                    lblDeleteMsgTitle.Text = "Excluir endereço";
                    popDeleteMsg.Show();
                    break;
                case "EditAddress":
                    LoadAddress(new Guid(e.CommandArgument.ToString()));
                    hidEditAddress.Value = e.CommandArgument.ToString();
                    btnCancelEditAddress.Visible = true;
                    btnAddAddress.Text = "Salvar";
                    break;
                default:
                    break;
            }
        }

        private void LoadAddress(Guid Id)
        {
            Data.EmployeeAddress address = this.CurrentEmployee.Addresses.FirstOrDefault(i => i.Id == Id);
            if (address != null)
            {
                ddlAddressType.SelectedValue = address.AddressType;
                txtAddress.Text = address.Address;
                txtAddressNumber.Text = address.Number;
                txtAdditionalAddress.Text = address.AdditionalAddress;
                txtZipCode.Text = address.ZipCode;
                txtNeighborhood.Text = address.Neighborhood;
                txtCity.Text = address.City;
                ddlState.SelectedValue = address.State;
                txtCountry.Text = address.Country;

                txtAddress.Focus();
            }
        }

        #endregion
    }
}